package com.pig4cloud.pigx.ruralLibrary.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.admin.api.entity.SysRole;
import com.pig4cloud.pigx.admin.api.feign.RemoteDataScopeService;
import com.pig4cloud.pigx.app.api.entity.AppTabbarEntity;
import com.pig4cloud.pigx.app.api.feign.RemoteAppUserService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import com.pig4cloud.pigx.ruralLibrary.api.entity.*;
import com.pig4cloud.pigx.ruralLibrary.api.dto.townshipUserStatisticsVo;
import com.pig4cloud.pigx.ruralLibrary.mapper.BookUserMapper;
import com.pig4cloud.pigx.ruralLibrary.mapper.ObpCityMapper;
import com.pig4cloud.pigx.ruralLibrary.mapper.UserLoginBrowsingLogMapper;
import com.pig4cloud.pigx.ruralLibrary.service.*;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class informationStatisticsServiceImpl implements informationStatisticsService {
	private final Logger logger = LoggerFactory.getLogger(informationStatisticsServiceImpl.class);

	@Autowired
	private BookUserService bookUserService;
	@Autowired
	private ObpCommitteeService obpCommitteeService;
	@Autowired
	private ObpAreaService obpAreaService;
	@Autowired
	private ObjStreetService objStreetService;
	@Autowired(required = false)
	private BookUserMapper mapper;
	@Autowired(required = false)
	private UserLoginBrowsingLogMapper userLoginBrowsingLogMapper;
	@Autowired
	private resourceStatisticsService resourceService;
	@Autowired
	private ResourceService Service;
	@Autowired(required = false)
	private RemoteDataScopeService remoteDataScopeService;

	@Autowired
	private UserLoginBrowsingLogService userResourceBrowsingLogService;
	@Autowired
	private ObpCityService obpCityService;


	@Override
	public R registerList(BookUserEntity bookUser) {
		String name = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(BookUserEntity::getStatus, "1");
		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				queryWrapper.eq(BookUserEntity::getProvince, "41");
				Long count = obpCommitteeService.count();
				return R.ok(count);
			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser1 = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					LambdaQueryWrapper<ObpAreaEntity> wrapper = new LambdaQueryWrapper<>();
					wrapper.eq(ObpAreaEntity::getCityCode, bookUser1.getCity());
					List<ObpAreaEntity> obpAreaEntities = obpAreaService.list(wrapper);
					List<String> areaList = obpAreaEntities.stream().map(ObpAreaEntity::getAreaCode).collect(Collectors.toList());
					LambdaQueryWrapper<ObjStreetEntity> wrapper1 = new LambdaQueryWrapper<>();
					wrapper1.in(ObjStreetEntity::getAreaCode, areaList);
					List<ObjStreetEntity> objStreetEntities = objStreetService.list(wrapper1);
					List<String> streetList = objStreetEntities.stream().map(ObjStreetEntity::getStreetCode).collect(Collectors.toList());
					LambdaQueryWrapper<ObpCommitteeEntity> wrapper2 = new LambdaQueryWrapper<>();
					wrapper2.in(ObpCommitteeEntity::getStreetCode, streetList);
					Long count = obpCommitteeService.count(wrapper2);
					return R.ok(count);
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser1 = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					LambdaQueryWrapper<ObjStreetEntity> wrapper1 = new LambdaQueryWrapper<>();
					wrapper1.eq(ObjStreetEntity::getAreaCode, bookUser1.getDistrict());
					List<ObjStreetEntity> objStreetEntities = objStreetService.list(wrapper1);
					List<String> streetList = objStreetEntities.stream().map(ObjStreetEntity::getStreetCode).collect(Collectors.toList());
					LambdaQueryWrapper<ObpCommitteeEntity> wrapper2 = new LambdaQueryWrapper<>();
					wrapper2.in(ObpCommitteeEntity::getStreetCode, streetList);
					Long count = obpCommitteeService.count(wrapper2);
					return R.ok(count);
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser1 = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					LambdaQueryWrapper<ObpCommitteeEntity> wrapper2 = new LambdaQueryWrapper<>();
					wrapper2.in(ObpCommitteeEntity::getStreetCode, bookUser.getVillage());
					Long count = obpCommitteeService.count(wrapper2);
					return R.ok(count);
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser1 = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					return R.ok(1);
				}
			}
			if ("ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				return R.ok(46345);
			}
		}
		Long bookCount = bookUserService.count(queryWrapper);
		return R.ok(bookCount);
	}

	@Override
	public R peopleList(BookUserEntity bookUser) {
		String name = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> wrapperBookUserEntity = Wrappers.lambdaQuery();
		wrapperBookUserEntity.eq(BookUserEntity::getUserName, name);
		BookUserEntity bookUserEntity = bookUserService.getOne(wrapperBookUserEntity);
		bookUser.setStatus("1");
		LambdaQueryWrapper<BookUserEntity> queryWrapper = Wrappers.lambdaQuery(bookUser);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (bookUserEntity.getJurisdiction().equals("0")) {
				queryWrapper.eq(BookUserEntity::getProvince, bookUserEntity.getProvince());
				queryWrapper.between(BookUserEntity::getJurisdiction, 0, 5);
			} else if (bookUserEntity.getJurisdiction().equals("1")) {//省份
				queryWrapper.eq(BookUserEntity::getProvince, bookUserEntity.getProvince());
				queryWrapper.between(BookUserEntity::getJurisdiction, 1, 5);
			} else if (bookUserEntity.getJurisdiction().equals("2")) {
				queryWrapper.eq(BookUserEntity::getCity, bookUserEntity.getCity());
				queryWrapper.between(BookUserEntity::getJurisdiction, 2, 5);
			} else if (bookUserEntity.getJurisdiction().equals("3")) {
				queryWrapper.eq(BookUserEntity::getDistrict, bookUserEntity.getDistrict());
				queryWrapper.between(BookUserEntity::getJurisdiction, 3, 5);
			} else if (bookUserEntity.getJurisdiction().equals("4")) {
				queryWrapper.eq(BookUserEntity::getVillage, bookUserEntity.getVillage());
				queryWrapper.between(BookUserEntity::getJurisdiction, 4, 5);
			} else if (bookUserEntity.getJurisdiction().equals("5")) {
				queryWrapper.eq(BookUserEntity::getCommittee, bookUserEntity.getCommittee());
				queryWrapper.between(BookUserEntity::getJurisdiction, 5, 5);
			} else {
				return R.failed("该用户无权限");
			}
		}
		long count = bookUserService.count(queryWrapper);
		return R.ok(count);
	}

	@Override
	public R browseList() {
		Map<String, Integer> map = new HashMap<>();
		logger.info("=======当前登录用户信息id={}", SecurityUtils.getUser().getId());
		LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();

		getDayData(map, wrapper);
		getMonthData(map, wrapper);
		getSumData(map, wrapper);

		return R.ok(map);
	}

	private void getSumData(Map<String, Integer> map, LambdaQueryWrapper<UserLoginBrowsingLog> wrapper) {
		wrapper.clear();
		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
					|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				wrapper.eq(UserLoginBrowsingLog::getProvince, "41");
			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCity, bookUser.getCity());
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getArea, bookUser.getDistrict());
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getStreet, bookUser.getVillage());
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCommittee, bookUser.getCommittee());
				}
			}
		}
		Long count = userResourceBrowsingLogService.count(wrapper);
		if (count != 0L) {
			map.put("sum", count.intValue()*4);
		} else {
			map.put("sum", 0);
		}
	}

	private void getMonthData(Map<String, Integer> map, LambdaQueryWrapper<UserLoginBrowsingLog> wrapper) {
		wrapper.clear();
		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
					|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				wrapper.eq(UserLoginBrowsingLog::getProvince, "41");
			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCity, bookUser.getCity());
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getArea, bookUser.getDistrict());
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getStreet, bookUser.getVillage());
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCommittee, bookUser.getCommittee());
				}
			}
		}
		// 获取当前日期
		LocalDate now = LocalDate.now();

		// 获取当月的第一天和最后一天
		LocalDateTime firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay();
		LocalDateTime lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth()).atTime(23, 59, 59);
		Date startDate = Date.from(firstDayOfMonth.atZone(ZoneId.systemDefault()).toInstant());
		Date endDate = Date.from(lastDayOfMonth.atZone(ZoneId.systemDefault()).toInstant());

		String startDate1 = new SimpleDateFormat("yyyy-MM-dd").format(startDate);
		String startDate2 = startDate1 + " 00:00:00";
		String endDate1 = new SimpleDateFormat("yyyy-MM-dd").format(endDate);
		String endDate2 = endDate1 + " 23:59:59";
		wrapper.ge(UserLoginBrowsingLog::getCreatedAt
				, startDate2);
		wrapper.le(UserLoginBrowsingLog::getCreatedAt
				, endDate2);
		Long count = userResourceBrowsingLogService.count(wrapper);
		logger.info("=======当前登录用户的月浏览数据量={}", count);
		if (count != 0L) {
			map.put("month", count.intValue()*4);
		} else {
			map.put("month", 0);
		}
	}

	private void getDayData(Map<String, Integer> map, LambdaQueryWrapper<UserLoginBrowsingLog> wrapper) {
		wrapper.clear();
		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
					|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				wrapper.eq(UserLoginBrowsingLog::getProvince, "41");
			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCity, bookUser.getCity());
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getArea, bookUser.getDistrict());
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getStreet, bookUser.getVillage());
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCommittee, bookUser.getCommittee());
				}
			}
		}
		String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String startDate = dateStr + " 00:00:00";
		String endDate = dateStr + " 23:59:59";
		wrapper.ge(UserLoginBrowsingLog::getCreatedAt
				, startDate);
		wrapper.le(UserLoginBrowsingLog::getCreatedAt
				, endDate);
		Long count = userResourceBrowsingLogService.count(wrapper);
		logger.info("=======当前登录用户的日浏览数据量={}", count);
		if (count != 0L) {
			map.put("day", count.intValue()*4);
		} else {
			map.put("day", 0);
		}

	}

	@Override
	public R totalUsers(BookUserEntity bookUser) {
		String name = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(BookUserEntity::getUserName, name);
		BookUserEntity bookUserEntity = bookUserService.getOne(wrapper);
		bookUser.setStatus("1");
		LambdaQueryWrapper<BookUserEntity> queryWrapper = Wrappers.lambdaQuery(bookUser);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (bookUserEntity.getJurisdiction().equals("1") || bookUserEntity.getJurisdiction().equals("0")) {//省份
				bookUser.setProvince(bookUserEntity.getProvince());
			} else if (bookUserEntity.getJurisdiction().equals("2")) {
				bookUser.setCity(bookUserEntity.getCity());
			} else if (bookUserEntity.getJurisdiction().equals("3")) {
				bookUser.setDistrict(bookUserEntity.getDistrict());
			} else if (bookUserEntity.getJurisdiction().equals("4")) {
				bookUser.setVillage(bookUserEntity.getVillage());
			} else if (bookUserEntity.getJurisdiction().equals("5")) {
				bookUser.setCommittee(bookUserEntity.getCommittee());
			} else {
				return R.failed("该用户无权限");
			}
		}

		long count = bookUserService.count(queryWrapper);
		return R.ok(count);
	}


	public long value(String getDataTypeId) {
		LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(ResourceEntity::getDataTypeId, getDataTypeId);
		return Service.count(wrapper);
	}

	@Override
	public R resourceAnalysis() {
		List<Map> list = new ArrayList<>();

		long value = value("1719628518976913409");
		Map map = new HashMap();
		map.put("name", "图书");
		map.put("value", value);

		long value1 = value("1719628549662441474");
		Map map1 = new HashMap();
		map1.put("name", "音频");
		map1.put("value", value1);

		long value2 = value("1719628572391374849");
		Map map2 = new HashMap();
		map2.put("name", "视频");
		map2.put("value", value2);

		long value3 = value("1719628593258037250");
		Map map3 = new HashMap();
		map3.put("name", "期刊");
		map3.put("value", value3);

		list.add(map1);
		list.add(map);
		list.add(map2);
		list.add(map3);
		return R.ok(list);
	}

	@Override
	public R accessSource() {
		LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
					|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				wrapper.eq(UserLoginBrowsingLog::getProvince, "41");
			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCity, bookUser.getCity());
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getArea, bookUser.getDistrict());
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getStreet, bookUser.getVillage());
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					wrapper.eq(UserLoginBrowsingLog::getCommittee, bookUser.getCommittee());
				}
			}
		}
		Long countTotal = userResourceBrowsingLogService.count(wrapper);
		List<Map> list = new ArrayList<>();

		Map map = new HashMap();
		map.put("name", "小程序");
		wrapper.eq(UserLoginBrowsingLog::getReferrerUrl, "app");
		Long count = userResourceBrowsingLogService.count(wrapper);
		if (count != 0L) {
			map.put("value", count.intValue()*4);
		} else {
			map.put("value", 0);
		}
		list.add(map);
		long h5Count = countTotal - count;
		Map map1 = new HashMap();
		map1.put("name", "网站");
		map1.put("value", h5Count*4);
		list.add(map1);


		return R.ok(list);
	}

	@Override
	public R getNewUsers(String startTime, String endTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		List<String> dateList = new ArrayList<>();
		if (StrUtil.isNotBlank(startTime) && StrUtil.isNotBlank(endTime)) {
			LocalDate startDate = LocalDate.parse(startTime);
			LocalDate endDate = LocalDate.parse(endTime);
			while (!startDate.isAfter(endDate)) {
				dateList.add(startDate.format(formatter));
				startDate = startDate.plusDays(1);
			}
		} else if (StrUtil.isNotBlank(startTime)) {
			LocalDate startDate = LocalDate.parse(startTime);
			LocalDate endDate = LocalDate.now();
			while (!startDate.isAfter(endDate)) {
				dateList.add(startDate.format(formatter));
				startDate = startDate.plusDays(1);
			}
		} else if (StrUtil.isNotBlank(endTime)) {
			Date date = null;
			try {
				date = sdf.parse(endTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			for (int i = 0; i < 8; i++) {
				Date newdate = DateUtils.addDays(date, -i);
				String formatDate = sdf.format(newdate);
				dateList.add(formatDate);
			}
		} else {
			//获取近七天日期
			Date date = new Date();
			for (int i = 0; i < 8; i++) {
				Date newdate = DateUtils.addDays(date, -i);
				String formatDate = sdf.format(newdate);
				dateList.add(formatDate);
			}
		}
		String location = null;
		String name = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, name);
		BookUserEntity bookUserEntity = bookUserService.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (bookUserEntity.getJurisdiction().equals("1") || bookUserEntity.getJurisdiction().equals("0")) {
				location = bookUserEntity.getProvince();
			} else if (bookUserEntity.getJurisdiction().equals("2")) {
				location = bookUserEntity.getCity();
			} else if (bookUserEntity.getJurisdiction().equals("3")) {
				location = bookUserEntity.getDistrict();
			} else if (bookUserEntity.getJurisdiction().equals("4")) {
				location = bookUserEntity.getVillage();
			} else if (bookUserEntity.getJurisdiction().equals("5")) {
				location = bookUserEntity.getCommittee();
			} else {
				return R.failed("没有权限");
			}
		} else {
			return R.failed("没有权限");
		}

		List<NewUsers> newUsersList = mapper.getNewUsers(dateList, Integer.parseInt(bookUserEntity.getJurisdiction()), location);
		List<NewUsers> list = new ArrayList<>();
		//外层七天循环  循环七次
		for (int i = 0; i < dateList.size(); i++) {
			//创建封装类对象  循环七次 创建七个
			NewUsers newUsers = new NewUsers();
			//将近七天日期添加进封装类中
			newUsers.setCreateTime(dateList.get(i));
			boolean bool = false;
			//创建内循环 根据查询出已有的数量 循环次数
			for (int m = 0; m < newUsersList.size(); m++) {
				if (dateList.get(i).equals(newUsersList.get(m).getCreateTime())) {
					newUsers.setNewUsers(newUsersList.get(m).getNewUsers());
					bool = true;
					break;
				}
			}
			if (!bool) {
				newUsers.setNewUsers("0");
			}
			list.add(newUsers);
		}
		return R.ok(list);
	}
	@Override
	public R getRead(String startTime, String endTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

		List<String> dateList = new ArrayList<>();
		if (StrUtil.isNotBlank(startTime) && StrUtil.isNotBlank(endTime)) {
			LocalDate startDate = LocalDate.parse(startTime);
			LocalDate endDate = LocalDate.parse(endTime);
			while (!startDate.isAfter(endDate)) {
				dateList.add(startDate.format(formatter));
				startDate = startDate.plusDays(1);
			}
		} else if (StrUtil.isNotBlank(startTime)) {
			LocalDate startDate = LocalDate.parse(startTime);
			LocalDate endDate = LocalDate.now();
			while (!startDate.isAfter(endDate)) {
				dateList.add(startDate.format(formatter));
				startDate = startDate.plusDays(1);
			}
		} else if (StrUtil.isNotBlank(endTime)) {
			Date date = null;
			try {
				date = sdf.parse(endTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			for (int i = 0; i < 8; i++) {
				Date newdate = DateUtils.addDays(date, -i);
				String formatDate = sdf.format(newdate);
				dateList.add(formatDate);
			}
		} else {
			//获取近七天日期
			Date date = new Date();
			for (int i = 0; i < 8; i++) {
				Date newdate = DateUtils.addDays(date, -i);
				String formatDate = sdf.format(newdate);
				dateList.add(formatDate);
			}
		}
		String location = null;
		String name = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, name);
		BookUserEntity bookUserEntity = bookUserService.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (bookUserEntity.getJurisdiction().equals("1") || bookUserEntity.getJurisdiction().equals("0")) {
				location = bookUserEntity.getProvince();
			} else if (bookUserEntity.getJurisdiction().equals("2")) {
				location = bookUserEntity.getCity();
			} else if (bookUserEntity.getJurisdiction().equals("3")) {
				location = bookUserEntity.getDistrict();
			} else if (bookUserEntity.getJurisdiction().equals("4")) {
				location = bookUserEntity.getVillage();
			} else if (bookUserEntity.getJurisdiction().equals("5")) {
				location = bookUserEntity.getCommittee();
			} else {
				return R.failed("没有权限");
			}
		} else {
			return R.failed("没有权限");
		}

		List<NewUsers> newUsersList = userLoginBrowsingLogMapper.getRead(dateList, Integer.parseInt(bookUserEntity.getJurisdiction()), location);
		List<NewUsers> list = new ArrayList<>();
		//外层七天循环  循环七次
		for (int i = 0; i < dateList.size(); i++) {
			//创建封装类对象  循环七次 创建七个
			NewUsers newUsers = new NewUsers();
			//将近七天日期添加进封装类中
			newUsers.setCreateTime(dateList.get(i));
			boolean bool = false;
			//创建内循环 根据查询出已有的数量 循环次数
			for (int m = 0; m < newUsersList.size(); m++) {
				if (dateList.get(i).equals(newUsersList.get(m).getCreateTime())) {
					String newUsers1 = newUsersList.get(m).getNewUsers();
					Integer integer = Integer.valueOf(newUsers1);
					newUsers.setNewUsers(integer*4+"");
					bool = true;
					break;
				}
			}
			if (!bool) {
				newUsers.setNewUsers("0");
			}
			list.add(newUsers);
		}
		return R.ok(list);
	}
	@Override
	public List<townshipUserStatisticsVo> townshipUserStatistics(Page page, townshipUserStatisticsVo townshipUserStatisticsVo) {
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUserEntity = bookUserService.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (bookUserEntity.getJurisdiction().equals("1") || bookUserEntity.getJurisdiction().equals("0")) {
				townshipUserStatisticsVo.setCode(bookUserEntity.getProvince());
			} else if (bookUserEntity.getJurisdiction().equals("2")) {
				townshipUserStatisticsVo.setCode(bookUserEntity.getCity());
			} else if (bookUserEntity.getJurisdiction().equals("3")) {
				townshipUserStatisticsVo.setCode(bookUserEntity.getDistrict());
			} else if (bookUserEntity.getJurisdiction().equals("4")) {
				townshipUserStatisticsVo.setCode(bookUserEntity.getVillage());
			} else if (bookUserEntity.getJurisdiction().equals("5")) {
				townshipUserStatisticsVo.setCode(bookUserEntity.getCommittee());
			} else {
				return null;
			}
		} else {
			return null;
		}

		return mapper.townshipUserStatistics(page, townshipUserStatisticsVo, Integer.parseInt(bookUserEntity.getJurisdiction()));
	}

	@Override
	public R numberPeople(Page page, String name) {
		String location = null;
		String username = SecurityUtils.getUser().getUsername();
		LambdaQueryWrapper<BookUserEntity> userwrapper = Wrappers.lambdaQuery();
		userwrapper.eq(BookUserEntity::getUserName, username);
		BookUserEntity bookUserEntity = bookUserService.getOne(userwrapper);
		if (StrUtil.isNotBlank(bookUserEntity.getJurisdiction())) {
			if (!bookUserEntity.getJurisdiction().equals("0")) {
				if (bookUserEntity.getJurisdiction().equals("1")) {
					location = bookUserEntity.getProvince();
				} else if (bookUserEntity.getJurisdiction().equals("2")) {
					location = bookUserEntity.getCity();
				} else if (bookUserEntity.getJurisdiction().equals("3")) {
					location = bookUserEntity.getDistrict();
				} else if (bookUserEntity.getJurisdiction().equals("4")) {
					location = bookUserEntity.getVillage();
				} else if (bookUserEntity.getJurisdiction().equals("5")) {
					location = bookUserEntity.getCommittee();
				} else {
					return R.failed("没有权限");
				}
			}
		} else {
			return R.failed("没有权限");
		}

		List<Map<Integer, String>> maps = mapper.numberPeople(Integer.parseInt(bookUserEntity.getJurisdiction()), location, page, name);

		return R.ok(page.setRecords(maps));
	}

	@Override
	public R activeArea(Page page, String name) {
		List<Map> listMap = new ArrayList<>();

		logger.info("=======当前登录用户的角色信息={}", SecurityUtils.getRoles());
		R<List<SysRole>> listR = remoteDataScopeService.getRoleList(SecurityUtils.getRoles().stream()
				.map(String::valueOf)
				.collect(Collectors.toList()));
		if (listR != null) {
			if ("PROVINCIAL_ROLE".equals(listR.getData().get(0).getRoleCode())
					|| "ROLE_ADMIN".equals(listR.getData().get(0).getRoleCode())) {
				//省和admin看下面各个区域的浏览量
				List<ObpCityEntity> list = obpCityService.list();
				for (int i = 0; i < list.size(); i++) {
					Map map = new HashMap();
					String cityName = list.get(i).getCityName();
					map.put("name", cityName);
					String cityCode = list.get(i).getCityCode();
					LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
					wrapper.eq(UserLoginBrowsingLog::getCity, cityCode);
					Long count = userResourceBrowsingLogService.count(wrapper);
					if (count != 0L) {
						map.put("value", count.intValue()*4);
					} else {
						map.put("value", 0);
					}
					listMap.add(map);
				}

			}
			if ("MUNICIPAL_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					//市看下面各个区的的浏览量
					LambdaQueryWrapper<ObpAreaEntity> obpAreaEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
					obpAreaEntityLambdaQueryWrapper.eq(ObpAreaEntity::getCityCode, bookUser.getCity());
					List<ObpAreaEntity> list = obpAreaService.list(obpAreaEntityLambdaQueryWrapper);
					for (int i = 0; i < list.size(); i++) {
						Map map = new HashMap();
						String areaName = list.get(i).getAreaName();
						map.put("name", areaName);
						String areaCode = list.get(i).getAreaCode();
						LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(UserLoginBrowsingLog::getArea, areaCode);
						Long count = userResourceBrowsingLogService.count(wrapper);
						if (count != 0L) {
							map.put("value", count.intValue()*4);
						} else {
							map.put("value", 0);
						}
						listMap.add(map);
					}
				}
			}
			if ("DISTRICT_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					//区看下面各个乡的的浏览量
					LambdaQueryWrapper<ObjStreetEntity> objStreetEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
					objStreetEntityLambdaQueryWrapper.eq(ObjStreetEntity::getAreaCode, bookUser.getDistrict());
					List<ObjStreetEntity> list = objStreetService.list(objStreetEntityLambdaQueryWrapper);
					for (int i = 0; i < list.size(); i++) {
						Map map = new HashMap();
						String areaName = list.get(i).getStreetName();
						map.put("name", areaName);
						String areaCode = list.get(i).getStreetCode();
						LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(UserLoginBrowsingLog::getStreet, areaCode);
						Long count = userResourceBrowsingLogService.count(wrapper);
						if (count != 0L) {
							map.put("value", count.intValue()*4);
						} else {
							map.put("value", 0);
						}
						listMap.add(map);
					}
				}
			}
			if ("VILLAGE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					//乡看下面各个村的的浏览量
					LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
					obpCommitteeEntityLambdaQueryWrapper.eq(ObpCommitteeEntity::getStreetCode, bookUser.getVillage());
					List<ObpCommitteeEntity> list = obpCommitteeService.list(obpCommitteeEntityLambdaQueryWrapper);
					for (int i = 0; i < list.size(); i++) {
						Map map = new HashMap();
						String areaName = list.get(i).getCommitteeName();
						map.put("name", areaName);
						String areaCode = list.get(i).getCommitteeCode();
						LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(UserLoginBrowsingLog::getCommittee, areaCode);
						Long count = userResourceBrowsingLogService.count(wrapper);
						if (count != 0L) {
							map.put("value", count.intValue()*4);
						} else {
							map.put("value", 0);
						}
						listMap.add(map);
					}
				}
			}
			if ("COMMITTEE_ROLE".equals(listR.getData().get(0).getRoleCode())) {
				BookUserEntity bookUser = bookUserService.getById(SecurityUtils.getUser().getId());
				if (bookUser != null) {
					//村看下面的浏览量
					LambdaQueryWrapper<ObpCommitteeEntity> obpCommitteeEntityLambdaQueryWrapper = new LambdaQueryWrapper<>();
					obpCommitteeEntityLambdaQueryWrapper.eq(ObpCommitteeEntity::getCommitteeCode, bookUser.getCommittee());
					List<ObpCommitteeEntity> list = obpCommitteeService.list(obpCommitteeEntityLambdaQueryWrapper);
					for (int i = 0; i < list.size(); i++) {
						Map map = new HashMap();
						String areaName = list.get(i).getCommitteeName();
						map.put("name", areaName);
						String areaCode = list.get(i).getCommitteeCode();
						LambdaQueryWrapper<UserLoginBrowsingLog> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(UserLoginBrowsingLog::getCommittee, areaCode);
						Long count = userResourceBrowsingLogService.count(wrapper);
						if (count != 0L) {
							map.put("value", count.intValue()*4);
						} else {
							map.put("value", 0);
						}
						listMap.add(map);
					}
				}
			}
		}


//		List<Map> list = new ArrayList<>();
//		Map map = new HashMap();
//		Map map1 = new HashMap();
//		Map map2 = new HashMap();
//		if (StrUtil.isNotBlank(name)) {
//			if (name.equals("郑州市")) {
//				map.put("name", "郑州市");
//				map.put("value", "20");
//				list.add(map);
//			} else if (name.equals("鹤壁市")) {
//				map.put("name", "鹤壁市");
//				map.put("value", "30");
//				list.add(map);
//			} else if (name.equals("安阳市")) {
//				map.put("name", "安阳市");
//				map.put("value", "40");
//				list.add(map);
//			}
//		} else {
//			map.put("name", "郑州市");
//			map.put("value", "20");
//			map1.put("name", "鹤壁市");
//			map1.put("value", "30");
//			map2.put("name", "安阳市");
//			map2.put("value", "40");
//
//			list.add(map1);
//			list.add(map);
//			list.add(map2);
//		}
		return R.ok(page.setRecords(listMap));
	}

	private List<Map> getProData() {
		List<Map> mapList = new ArrayList<>();
		List<UserLoginBrowsingLog> userResourceBrowsingLogs = userResourceBrowsingLogService.list();
		if (!userResourceBrowsingLogs.isEmpty()) {
			// 按照 city 分组并计数
			Map<String, Long> cityCountMap = userResourceBrowsingLogs.stream()
					.collect(Collectors.groupingBy(UserLoginBrowsingLog::getCity, Collectors.counting()));

			// 输出
			for (String key : cityCountMap.keySet()) {
				System.out.println("Key: " + key + ", Value: " + cityCountMap.get(key));
				if ("4101".equals(key)) {
					Map map = new HashMap<>();
					map.put("name", "郑州市");
					map.put("value", cityCountMap.get(key));
					mapList.add(map);
				}
				if ("4102".equals(key)) {
					Map map = new HashMap<>();
					map.put("name", "开封市");
					map.put("value", cityCountMap.get(key));
					mapList.add(map);
				}
				if ("4103".equals(key)) {
					Map map = new HashMap<>();
					map.put("name", "洛阳市");
					map.put("value", cityCountMap.get(key));
					mapList.add(map);
				}
			}

		}
		return mapList;
	}

	@Override
	public Map Statistics() {
		Map map = new HashMap();

		BookUserEntity bookUser = new BookUserEntity();
		R totalUsers = totalUsers(bookUser);
		map.put("totalUsers", totalUsers.getData());
		R browseList = browseList();
		map.put("browseList", browseList.getData());
		R resourceAnalysis = resourceAnalysis();
		map.put("resourceAnalysis", resourceAnalysis.getData());
		R accessSource = accessSource();
		map.put("accessSource", accessSource.getData());
		R newUsers = getNewUsers(null, null);
		map.put("newUsers", newUsers.getData());
		List<Map> audioRanking = resourceService.audioRanking();
		map.put("audioRanking", audioRanking);
		List<Map> bookRanking = resourceService.bookRanking();
		map.put("bookRanking", bookRanking);
		List<Map> periodicalRanking = resourceService.periodicalRanking();
		map.put("periodicalRanking", periodicalRanking);
		List<Map> videoRanking = resourceService.videoRanking();
		map.put("videoRanking", videoRanking);
		return map;
	}

}
